package com.yiya.ms.action;

import java.beans.PropertyEditorSupport;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.yiya.bean.Car;
import com.yiya.bean.SysUser;
import com.yiya.model.CarModel;
import com.yiya.service.CarService;
import com.yiya.utils.DataTypeUtil;
import com.yiya.utils.HtmlUtil;
import com.yiya.utils.SessionUtils;

@Controller
@RequestMapping("/car")
public class CarAction extends BaseAction{
	@SuppressWarnings("unused")
	private final static Logger log = Logger.getLogger(CarAction.class);
	
	
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
		    public void setAsText(String value) {
		        try {
		            setValue(new SimpleDateFormat("yyyy-MM-dd").parse(value));
		        } catch(ParseException e) {
		            setValue(null);
		        }
		    }
		    public String getAsText() {
		        return new SimpleDateFormat("yyyy-MM-dd").format((Date) getValue());
		    }        
		});
	}
	@Autowired
	private CarService carService;
	
	@RequestMapping("/list") 
	public ModelAndView list(HttpServletRequest request){
		Map<String,Object>  context = getRootMap();
		return forword("car/car",context); 
	}
	
	@RequestMapping("/dataList") 
	public void  datalist(CarModel model,HttpServletResponse response) throws Exception{
		List<Car> cars = carService.queryByList(model);
		int count = carService.queryByCount(model);
		
		Float amountSum = 0f;
		List<Map<String, Object>> footer = new ArrayList<Map<String, Object>>();
		for(Car car:cars){
			amountSum+=car.getAmount()==null?0:car.getAmount();
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("number", "合计：");		
		map.put("amount", DataTypeUtil.KeepDecimal(2, amountSum));
		footer.add(map);
		
		//设置页面数据
		Map<String,Object> jsonMap = new HashMap<String,Object>();
		jsonMap.put("rows", cars);
		jsonMap.put("total", count);
		jsonMap.put("footer", footer);
		HtmlUtil.writerJson(response, jsonMap);
		
	}
	
	@RequestMapping("/save")
	public void save(Car bean,HttpServletRequest request,HttpServletResponse response){
		Date nowTime = new Date();
		SysUser user = SessionUtils.getUser(request);
		if(bean.getId() == null){
			bean.setCreateTime(nowTime);
			bean.setCreateBy(user.getId());
			carService.add(bean);
		}else{
			bean.setUpdateBy(user.getId());
			bean.setUpdateTime(nowTime);
			carService.Update(bean);
		}
		sendSuccessMessage(response, "保存成功");
	}
	
	@RequestMapping("/getId")
	public void getId(Integer id,HttpServletResponse response){
		Map<String,Object>  context = getRootMap();
		Car car = carService.queryById(id);
		if(car  == null){
			sendFailureMessage(response, "没有找到对应的记录!");
			return;
		}
		context.put(SUCCESS, true);
		context.put("data", car);
		HtmlUtil.writerJson(response, context);
	}
	
	@RequestMapping("/delete")
	public void delete(Integer[] id,HttpServletRequest request,HttpServletResponse response) throws Exception{
		SysUser user = SessionUtils.getUser(request);
		carService.delete(id,user);
		sendSuccessMessage(response, "删除成功");
	}
	
	@RequestMapping("/export_car")
	public void exportOutBill(CarModel model,HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		List<Car> cars = carService.queryAllByList(model);
		HSSFWorkbook wb = carService.export(cars);
		response.setContentType("application/vnd.ms-excel");
		response.setHeader("Content-disposition", "attachment;filename="+format.format(date)+".xls"); 
		OutputStream ouputStream = response.getOutputStream();
		wb.write(ouputStream);    
        ouputStream.flush();    
        ouputStream.close(); 
	}
}
